#include "CountDownLatch.hpp"

using namespace DBServer::Log;

CountDownLatch::CountDownLatch(int count)
  : count_(count)
{}

void CountDownLatch::wait()
{
    std::unique_lock<std::mutex> lock(mutex_);
    condition_.wait(lock, [this]{ 
        return this->count_ == 0;
    });
}

void CountDownLatch::count_down()
{
    std::unique_lock<std::mutex> lock(mutex_);
    --count_;
    if (count_ == 0)
    {
        condition_.notify_all();
    }
}

int CountDownLatch::get_count()
{
    std::unique_lock<std::mutex> lock(mutex_);
    return count_;
}



#if 0

#include <thread>
#include <iostream>
#include <vector>

int main()
{
    using namespace std;
    std::vector<thread> pool;
    CountDownLatch cdl(10);
    for (int i = 0; i < 10; ++i)
    {
        pool.emplace_back([&cdl, i]{
            cout << "thread " << i << endl;
            if (i == 9) usleep(1000);
            cdl.count_down();
            cdl.wait();
            cout << "thread " << i  << "finish" << endl;
        });
    }
    for (auto& t : pool)
    {
        t.join();
    }
}

#endif